package com.huashi.dealer.modular.business.goods.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huashi.dealer.commonEntity.Goods;
import com.huashi.dealer.core.util.TimeUtil;
import com.huashi.dealer.modular.business.goods.mapper.GiftGoodsMapper;
import com.huashi.dealer.modular.business.goods.param.GiftGoodsListParam;
import com.huashi.dealer.modular.business.goods.param.GiftGoodsSaveParam;
import com.huashi.dealer.modular.business.goods.service.GiftGoodsService;
import com.huashi.dealer.modular.business.goods.vo.GiftGoodsVo;
import com.huashi.dealer.modular.business.goods.mapper.GoodsImageMapper;
import com.huashi.dealer.modular.business.category.mapper.GiftCategoryMapper;
import com.huashi.dealer.commonEntity.Category;
import com.huashi.dealer.commonEntity.GoodsImage;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GiftGoodsServiceImpl extends ServiceImpl<GiftGoodsMapper, Goods> implements GiftGoodsService {

    @Resource
    private GiftGoodsMapper giftGoodsMapper;

    @Resource
    private GoodsImageMapper goodsImageMapper;

    @Resource
    private GiftCategoryMapper giftCategoryMapper;

    @Override
    public Page<GiftGoodsVo> getGiftGoodsList(GiftGoodsListParam param, Page<Goods> page) {
        // 构建查询条件
        LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Goods::getIsType, 20); // 固定为赠品类型

        // 状态筛选
        if (param.getStatus() != null) {
            queryWrapper.eq(Goods::getGoodsStatus, param.getStatus());
        }

        // 分类筛选
        if (param.getCategoryId() != null && param.getCategoryId() > 0) {
            queryWrapper.eq(Goods::getCategoryId, param.getCategoryId());
        }

        // 搜索关键词
        if (StringUtils.hasText(param.getSearch())) {
            queryWrapper.like(Goods::getGoodsName, param.getSearch());
        }

        // 排序
        if ("sales".equals(param.getSortType())) {
            queryWrapper.orderByDesc(Goods::getSalesActual);
        } else if ("price".equals(param.getSortType())) {
            if (Boolean.TRUE.equals(param.getSortPrice())) {
                queryWrapper.orderByDesc(Goods::getGoodsPrice);
            } else {
                queryWrapper.orderByAsc(Goods::getGoodsPrice);
            }
        } else {
            // 默认排序
            queryWrapper.orderByAsc(Goods::getGoodsSort)
                    .orderByDesc(Goods::getGoodsId);
        }

        // 执行分页查询
        Page<Goods> goodsPage = giftGoodsMapper.selectPage(page, queryWrapper);
        
        // 转换为VO
        List<GiftGoodsVo> voList = goodsPage.getRecords().stream()
                .map(this::convertToVo)
                .collect(Collectors.toList());

        // 构建返回结果
        Page<GiftGoodsVo> resultPage = new Page<>();
        resultPage.setRecords(voList);
        resultPage.setTotal(goodsPage.getTotal());
        resultPage.setSize(goodsPage.getSize());
        resultPage.setCurrent(goodsPage.getCurrent());

        return resultPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveOrUpdateGoods(GiftGoodsSaveParam param) {
        Goods goods = new Goods();
        goods.setGoodsId(param.getGoodsId());
        goods.setGoodsName(param.getGoodsName());
        goods.setCategoryId(param.getCategoryId());
        goods.setBarCode(param.getBarCode());
        goods.setSellingPoint(param.getSellingPoint());
        goods.setContent(param.getContent());
        goods.setGoodsSort(param.getGoodsSort());
        goods.setGoodsStatus(param.getGoodsStatus());
        goods.setSalesInitial(param.getSalesInitial());
        goods.setGiftStockNum(param.getStockNum());
        goods.setIsType(20); // 固定为赠品类型
        goods.setSpecType(10); // 固定为单规格
        goods.setCreateTime(System.currentTimeMillis() / 1000);

        if (param.getGoodsId() == null) {
            // 新增
            giftGoodsMapper.insert(goods);
        } else {
            // 编辑
            goods.setUpdateTime(System.currentTimeMillis() / 1000);
            giftGoodsMapper.updateById(goods);
        }

        // 处理商品图片关联
        if (param.getImageIds() != null && !param.getImageIds().isEmpty()) {
            saveGoodsImages(goods.getGoodsId(), param.getImageIds());
        }
    }

    /**
     * 保存商品图片关联
     */
    private void saveGoodsImages(Long goodsId, List<Long> imageIds) {
        // 先删除旧的图片关联
        LambdaQueryWrapper<GoodsImage> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(GoodsImage::getGoodsId, goodsId);
        goodsImageMapper.delete(deleteWrapper);

        // 保存新的图片关联
        for (Long imageId : imageIds) {
            GoodsImage goodsImage = new GoodsImage();
            goodsImage.setGoodsId(goodsId);
            goodsImage.setImageId(imageId);
            goodsImage.setCreateTime(System.currentTimeMillis() / 1000);
            goodsImageMapper.insert(goodsImage);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteGoods(Long goodsId) {
        giftGoodsMapper.deleteById(goodsId);
    }

    @Override
    public GiftGoodsVo getGoodsDetail(Long goodsId) {
        Goods goods = giftGoodsMapper.selectById(goodsId);
        if (goods == null) {
            return null;
        }
        return convertToVo(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateGoodsStatus(Long goodsId, Integer status) {
        Goods goods = new Goods();
        goods.setGoodsId(goodsId);
        goods.setGoodsStatus(status);
        goods.setUpdateTime(System.currentTimeMillis() / 1000);
        giftGoodsMapper.updateById(goods);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyGoods(Long goodsId) {
        Goods originalGoods = giftGoodsMapper.selectById(goodsId);
        if (originalGoods == null) {
            throw new RuntimeException("原商品不存在");
        }

        // 创建新商品
        Goods newGoods = new Goods();
        newGoods.setGoodsName(originalGoods.getGoodsName() + "_复制");
        newGoods.setCategoryId(originalGoods.getCategoryId());
        newGoods.setBarCode(originalGoods.getBarCode());
        newGoods.setSellingPoint(originalGoods.getSellingPoint());
        newGoods.setContent(originalGoods.getContent());
        newGoods.setGoodsSort(originalGoods.getGoodsSort());
        newGoods.setGoodsStatus(20); // 复制后默认下架
        newGoods.setSalesInitial(originalGoods.getSalesInitial());
        newGoods.setIsType(20);
        newGoods.setSpecType(10); // 固定为单规格
        newGoods.setCreateTime(System.currentTimeMillis() / 1000);

        giftGoodsMapper.insert(newGoods);

        // 复制商品图片
        List<GoodsImage> originalImageList = goodsImageMapper.selectByGoodsId(goodsId);
        for (GoodsImage originalImage : originalImageList) {
            GoodsImage newImage = new GoodsImage();
            newImage.setGoodsId(newGoods.getGoodsId());
            newImage.setImageId(originalImage.getImageId());
            newImage.setCreateTime(System.currentTimeMillis() / 1000);
            goodsImageMapper.insert(newImage);
        }
    }

    /**
     * 转换为VO
     */
    private GiftGoodsVo convertToVo(Goods goods) {
        GiftGoodsVo vo = new GiftGoodsVo();
        vo.setGoodsId(goods.getGoodsId());
        vo.setGoodsName(goods.getGoodsName());
        vo.setCategoryId(goods.getCategoryId());
        vo.setBarCode(goods.getBarCode());
        vo.setSellingPoint(goods.getSellingPoint());
        vo.setGiftStockNum(goods.getGiftStockNum());
        vo.setSalesActual(goods.getSalesActual());
        vo.setGoodsSort(goods.getGoodsSort());
        vo.setGoodsStatus(goods.getGoodsStatus());
        vo.setCreateTime(TimeUtil.changeToLocalDateTime(goods.getCreateTime()));

        // 设置状态文本
        if (goods.getGoodsStatus() != null) {
            vo.setGoodsStatusText(goods.getGoodsStatus() == 10 ? "上架" : "下架");
        }

        // 设置分类名称
        if (goods.getCategoryId() != null) {
            Category category = giftCategoryMapper.selectById(goods.getCategoryId());
            if (category != null) {
                vo.setCategoryName(category.getName());
            }
        }

        // 设置商品图片
        if (goods.getGoodsId() != null) {
            List<String> imageUrls = goodsImageMapper.getFileUrlByGoodsId(goods.getGoodsId());
            vo.setImageUrls(imageUrls);
        }

        return vo;
    }
}
